# -*- coding: utf-8 -*-

import logging
from time import time

from flask import url_for
# from itsdangerous import URLSafeSerializer, BadSignature

from mpdev.exceptions import BadConfigurationError

from .zeroleo12345_crypt import Zeroleo12345Crypt

logger = logging.getLogger(__name__)


class Serializer:
    def __init__(self, app=None):
        self.app = None
        self.serializer = None
        self.secret_key = None
        self.serializer_salt = None
        if app is not None:
            pass

    def init_app(self, app):
        # self.secret_key = app.config.get('SECRET_KEY')
        # if self.secret_key is None:
        #     raise BadConfigurationError('没有设置SECRET_KEY')
        # self.serializer_salt = app.config.get('SERIALIZER_SALT')
        # if self.serializer_salt is None:
        #     raise BadConfigurationError('没有设置SERIALIZER_SALT')

        # self.serializer = Zeroleo12345Crypt(
        #     self.secret_key,
        #     salt=self.serializer_salt
        # )

        self.serializer = Zeroleo12345Crypt()
        self.app = app
        app.serializer = self

        logger.debug('Serializer initialized.')

    def generate_room_url(self, room_id):
        ts = str(int(time()))
        enc_room_id = self.serializer.dumps(room_id, ts)
        # CAUTION: 需要在oauth部分处理ts的传递
        return url_for('gzone.index', enc_room_id=enc_room_id, ts=ts)

    def dehash_room_id(self, hashed_room_id, ts):
        try:
            room_id = self.serializer.loads(hashed_room_id, ts)
        except:
            # todo: room_id验证失败情况下跳转页面
            logger.warning(
                'Enc roomid dehash FAILED. enc_room_id: %s. ts: %s',
                hashed_room_id,
                ts
            )
            return None
        logger.debug(
            'Enc roomid dehash PASSED. enc_room_id: %s. ts: %s. room_id: %s',
            hashed_room_id,
            ts,
            room_id
        )
        return room_id

    def dumps(self, obj):
        return self.serializer.dumps(obj)
